package graphique;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

import executer.Controleur;


public class FormulaireCompte extends JFrame{

	private static final long serialVersionUID = 1L;
	private JLabel nomLabel2, prenomLabel, passwordLabel, passwordLabel2, 
			annifLabel, rueLabel, villeLabel, paysLabel, telPortLabel, telFixeLabel, telBureauLabel, emailLabel, 
			arobLabel, pointLabel, obl;
	private JTextField nom2, prenom, rue, ville, pays,
			emailPart1, emailPart2, emailPart3;
	private JPasswordField password, password2;
	private Font police = new Font("Arial", Font.BOLD, 12);
	
	@SuppressWarnings("unused")
	private JComboBox comboMonth,comboDay,comboYear;
	private JButton cal, valide, annuler, okannif;
	private Calendrier c;
	private JFormattedTextField telPort, telFixe, telBureau;
	private Controleur control;
	private CalDateN cdn = new CalDateN(this);
	
	//variable servant a stocker les donnees entrees par l'utilisateur
	private String nomU = null, prenomU = null, dateU = null, telpU = null, telfU = null, telbU = null, 
			rueU = null, villeU = null, paysU = null, emailU = null, pwdU1 = null, pwdU2 = null, pseudo = null;
			
	/**
	 * Constructeur
	 * @param parent
	 * @param title
	 * @param modal
	 */
	public FormulaireCompte(String str, Controleur control, String pseudo){
		super(str);
		this.control = control;
		this.pseudo = pseudo;
		this.setSize(400, 600);
		this.setLocationRelativeTo(null);
		this.setResizable(false);
		//termine le processus lorsque l'on clic sur la croix
		this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		this.initForm();
		this.setVisible(true);
	}

	
	
	public void setUserDate(String dt) {
		dateU = dt;
	}

	//@SuppressWarnings("deprecation")
	@SuppressWarnings("deprecation")
	public void initForm(){
		setLayout(new GridLayout(1, 6));
		
		//cadre identifiant
		JPanel panLog = new JPanel();
		
		panLog.setBackground(Color.white);
		panLog.setPreferredSize(new Dimension(300, 220)); //dimension du cadre
		
		panLog.setBorder(BorderFactory.createTitledBorder("Informations Personnelles"));
		
		//zone nom
		nom2 = new JTextField("");
		nom2.setPreferredSize(new Dimension(130, 25));
        nom2.setForeground(Color.black);
        nom2.setFont(police);
		nomLabel2 = new JLabel("Nom* :");
		Box hBox7 = Box.createHorizontalBox();
        hBox7.add(nomLabel2);
        hBox7.add(Box.createHorizontalStrut(70));
        hBox7.add(nom2);
		
		//zone prenom
		prenom = new JTextField("");
		prenom.setPreferredSize(new Dimension(130, 25));
        prenom.setForeground(Color.black);
        prenom.setFont(police);
		prenomLabel = new JLabel("Prenom* :");
		Box hBox8 = Box.createHorizontalBox();
        hBox8.add(prenomLabel);
        hBox8.add(Box.createHorizontalStrut(50));
        hBox8.add(prenom);
		
		//zone adresse
        rueLabel = new JLabel("Rue :");
        rue = new JTextField("");
        rue.setPreferredSize(new Dimension(100, 25));
        Box hBox10 = Box.createHorizontalBox();
        hBox10.add(rueLabel);
        hBox10.add(Box.createHorizontalStrut(30));
        hBox10.add(rue); 
        
        villeLabel = new JLabel("Ville :");
        ville = new JTextField("");
        ville.setPreferredSize(new Dimension(100, 25));
        Box hBox11 = Box.createHorizontalBox();
        hBox11.add(villeLabel);
        hBox11.add(Box.createHorizontalStrut(75));
        hBox11.add(ville); 
        
        paysLabel = new JLabel("Pays :");
        pays = new JTextField("");
        pays.setPreferredSize(new Dimension(100, 25));
        Box hBox12 = Box.createHorizontalBox();
        hBox12.add(paysLabel);
        hBox12.add(Box.createHorizontalStrut(70));
        hBox12.add(pays); 
		
		//zone date de naissance
		annifLabel = new JLabel("Date de naissance* :");
		//panLog.add(annifLabel);
		/*dateAnnif = new JFormattedTextField(DateFormat.getDateInstance());
		dateAnnif.setPreferredSize(new Dimension(100, 25));
		try{
        	   MaskFormatter dateA = new MaskFormatter(dateU);
        	   dateAnnif = new JFormattedTextField(dateA);
        }catch(ParseException e){
        	e.printStackTrace();
        }
		*/
		cal = new JButton("annee de naissance");
		cal.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				cdn.setVisible(true);
				
				
			}
		});
		Box hBox9 = Box.createHorizontalBox();
        hBox9.add(annifLabel);
        //hBox9.add(Box.createHorizontalStrut(5));
        //hBox9.add(dateAnnif);
        hBox9.add(Box.createHorizontalStrut(5));
        hBox9.add(cal);
		
		
		//creation de la liste du choix de l'annee
		int n=100, j=0;
		int fin = (new Date()).getYear() + 1900;//permet de selectionner l'annee courante, chaque annee la liste s'incrementera toute seule
		String tabYear[] = new String[n];
		//boucle pour remplir la liste avec les 100 derni�res annees
		for (int i=fin;i>fin-n; i--){
				tabYear[j]=String.valueOf(i);
				j++;
		}
		comboYear = new JComboBox(tabYear);
		comboYear.addItemListener(new ItemState());
		comboYear.addActionListener(new ItemAction());
		//panLog.add(comboYear);
		
		//creation de la liste des mois
		String[] tabMonth = {"Janvier", "Fevrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre"};
		
		comboMonth = new JComboBox(tabMonth);
		comboMonth.addItemListener(new ItemState());
		comboMonth.addActionListener(new ItemAction());
		//panLog.add(comboMonth);
		
		//creation de la liste des jours
		int indexmois = comboMonth.getSelectedIndex();
		int annee = Integer.parseInt((String)comboYear.getSelectedItem());
		GregorianCalendar cal = new GregorianCalendar();
		boolean isLeap = cal.isLeapYear(annee);
		System.out.println(isLeap);
		//int tabjour[][];
		
		//Map<bool, tabjour>;
		String tabDay[];
		int days = getDays(indexmois, isLeap);		
		
		//int m=31;
		tabDay = new String[days];
	
		for(int i=0;i<days;i++)
		{
			tabDay[i]= String.valueOf(i+1);
		}		
		
		comboDay = new JComboBox(tabDay);		
		
		Box vBox3 = Box.createVerticalBox();
        vBox3.add(hBox7);
        vBox3.add(Box.createVerticalStrut(5));
        vBox3.add(hBox8);
        vBox3.add(Box.createVerticalStrut(5));
        vBox3.add(hBox10);
        vBox3.add(Box.createVerticalStrut(5));
        vBox3.add(hBox11);
        vBox3.add(Box.createVerticalStrut(5));
        vBox3.add(hBox12);
        vBox3.add(Box.createVerticalStrut(5));
        vBox3.add(hBox9);
        panLog.add(vBox3);
		
		//cadre contact
		JPanel panCon = new JPanel();
		
		panCon.setBackground(Color.white);
		panCon.setPreferredSize(new Dimension(300, 160)); //dimension du cadre
		panCon.setBorder(BorderFactory.createTitledBorder("Contacts (*)"));
				
		telPort = new JFormattedTextField(NumberFormat.getIntegerInstance());
		telFixe = new JFormattedTextField(NumberFormat.getIntegerInstance());
		telBureau = new JFormattedTextField(NumberFormat.getIntegerInstance());
		try{
        	   MaskFormatter telP = new MaskFormatter("##-##-##-##-##");
        	   MaskFormatter telF = new MaskFormatter("##-##-##-##-##");
        	   MaskFormatter telB = new MaskFormatter("##-##-##-##-##");
        	   telPort = new JFormattedTextField(telP);
        	   telFixe = new JFormattedTextField(telF);
        	   telBureau = new JFormattedTextField(telB);
        }catch(ParseException e){
        	e.printStackTrace();
        }

		telPort.setPreferredSize(new Dimension(100, 25));
		telPortLabel = new JLabel("Telephone mobile :");
		Box hBox1 = Box.createHorizontalBox();
        hBox1.add(telPortLabel);
        hBox1.add(Box.createHorizontalStrut(15));
        hBox1.add(telPort);

		telFixe.setPreferredSize(new Dimension(100, 25));
		telFixeLabel = new JLabel("Telephone fixe :");
		Box hBox3 = Box.createHorizontalBox();
        hBox3.add(telFixeLabel);
        hBox3.add(Box.createHorizontalStrut(30));
        hBox3.add(telFixe);
        
		telBureau.setPreferredSize(new Dimension(100, 25));
		telBureauLabel = new JLabel("Telephone bureau :");
		Box hBox4 = Box.createHorizontalBox();
        hBox4.add(telBureauLabel);
        hBox4.add(Box.createHorizontalStrut(15));
        hBox4.add(telBureau);
		
		emailLabel = new JLabel("Email :");
		arobLabel = new JLabel("@");
		pointLabel = new JLabel(".");
		emailPart1 = new JTextField("");
		emailPart1.setPreferredSize(new Dimension(80, 25));
		emailPart2 = new JTextField("");
		emailPart2.setPreferredSize(new Dimension(40, 25));
		emailPart3 = new JTextField("");
		emailPart3.setPreferredSize(new Dimension(20, 25));
		Box hBox2 = Box.createHorizontalBox();
        hBox2.add(emailLabel);
        hBox2.add(Box.createHorizontalStrut(2));
        hBox2.add(emailPart1);
        hBox2.add(Box.createHorizontalStrut(2));
        hBox2.add(arobLabel);
        hBox2.add(Box.createHorizontalStrut(2));
        hBox2.add(emailPart2);
        hBox2.add(Box.createHorizontalStrut(2));
        hBox2.add(pointLabel);
        hBox2.add(Box.createHorizontalStrut(2));
        hBox2.add(emailPart3);
        
        Box vBox = Box.createVerticalBox();
        vBox.add(hBox1);
        vBox.add(Box.createVerticalStrut(5));
        vBox.add(hBox3);
        vBox.add(Box.createVerticalStrut(5));
        vBox.add(hBox4);
        vBox.add(Box.createVerticalStrut(5));
        vBox.add(hBox2);
        panCon.add(vBox);

		
		//cadre mot de passe
		
		JPanel panPwd = new JPanel();
		
		panPwd.setBackground(Color.white);
		panPwd.setPreferredSize(new Dimension(300, 100)); //dimension du cadre
		
		//zone password saisie 1
		panPwd.setBorder(BorderFactory.createTitledBorder("Mot de passe (*)"));
		password = new JPasswordField("");
		password.setPreferredSize(new Dimension(100, 25));
		passwordLabel = new JLabel("Mot de passe* :");
		panPwd.add(passwordLabel);
		panPwd.add(password);
		Box hBox5 = Box.createHorizontalBox();
        hBox5.add(passwordLabel);
        hBox5.add(Box.createHorizontalStrut(80));
        hBox5.add(password);
		
		//zone password saisie 2
		password2 = new JPasswordField("");
		password2.setPreferredSize(new Dimension(100, 25));
		passwordLabel2 = new JLabel("Confirmer le mot de passe* :");
		Box hBox6 = Box.createHorizontalBox();
        hBox6.add(passwordLabel2);
        hBox6.add(Box.createHorizontalStrut(5));
        hBox6.add(password2);
		
        Box vBox2 = Box.createVerticalBox();
        vBox2.add(hBox5);
        vBox2.add(Box.createVerticalStrut(5));
        vBox2.add(hBox6);
        panPwd.add(vBox2);
		
        valide = new JButton("Creer Compte");
        valide.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				nomU = nom2.getText();
				prenomU = prenom.getText();
				//dateU = dateAnnif.getText();
				rueU = rue.getText();
				villeU = ville.getText();
				paysU = pays.getText();
				telpU = telPort.getText();
				telfU = telFixe.getText();
				telbU = telBureau.getText();
				emailU = emailPart1.getText() + "@" + emailPart2.getText() + "." + emailPart3.getText();
				pwdU1 = password.getText();
				pwdU2 = password2.getText();
				//System.out.println(nomU + " " + prenomU + " " + dateU + " " + rueU + " " + emailU + " " + pwdU1 + " " + pwdU2);
				if(pwdU1.compareTo(pwdU2)!=0 || pwdU1.isEmpty() || nomU.isEmpty() || prenomU.isEmpty() || dateU.isEmpty()){
					boitePwdErreur();
				} else {
					boiteSucces();
					Map<String, String> data = new HashMap<String, String>();
					data.put("nom", nomU);
					data.put("prenom", prenomU);
					data.put("anniv", dateU);
					data.put("adresse", rueU);
					data.put("cp", villeU);
					data.put("pays", paysU);
					data.put("fixe", telfU);
					data.put("port", telpU);
					data.put("bureau", telbU);
					data.put("email", emailU);
					data.put("login", pseudo);
					data.put("pass", pwdU1);
					FormulaireCompte.this.control.newOwner(data);
					dispose();
				}
					
			}
		});
        
        annuler = new JButton("Annuler");
        annuler.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent event){
    			dispose();
    		}
    	});
        
        obl = new JLabel("* champs obligatoire");
        obl.setFont(new Font("ARIAL",Font.ITALIC,10));
		
		JPanel content1 = new JPanel();
		content1.setBackground(Color.white);
		content1.add(panLog);
		content1.add(panCon);
		content1.add(panPwd);
		content1.add(valide);
		content1.add(annuler);
		content1.add(obl);
		add(content1, BorderLayout.NORTH);
		
	}
	
	/*public void anneeN(String[] tabFevrier){
		for(int i=0;i<29;i++){
			tabFevrier[i]=String.valueOf(i+1);
		}
	}
	
	public void anneeB(String[] tabFevrier){
		for(int i=0;i<30;i++){
			tabFevrier[i]=String.valueOf(i+1);
		}
	}*/
	
	
	/**
     * Classe interne implementant l'interface ItemListener
     */
        class ItemState implements ItemListener{
 
        	public void itemStateChanged(ItemEvent e) {
                        System.out.println("evenement declenche sur : " + e.getItem());
                    //panLog.remove(comboDay);
                    /*boolean bool = (new GregorianCalendar()).isLeapYear(Integer.parseInt((String)comboYear.getSelectedItem()));
                    int days = getDays(comboMonth.getSelectedIndex(), bool);
                    String[] tabDay = new String[days];
                    for(int i=0;i<days;i++)
        			{
        				tabDay[i]= String.valueOf(i+1);
        			}
                    comboDay = new JComboBox(tabDay);
                    panLog.add(comboDay);
                    panLog.resetKeyboardActions();*/
                    
            }               
    }
    
    class ItemAction implements ActionListener{
    	 
        public void actionPerformed(ActionEvent e) {
                System.out.println("ActionListener : action sur " + comboMonth.getSelectedItem());
                //panLog.remove(comboDay);
                /*boolean bool = (new GregorianCalendar()).isLeapYear(Integer.parseInt((String)comboYear.getSelectedItem()));
                int days = getDays(comboMonth.getSelectedIndex(), bool);
                String[] tabDay = new String[days];
                for(int i=0;i<days;i++)
    			{
    				tabDay[i]= String.valueOf(i+1);
    			}
                comboDay = new JComboBox(tabDay);
                panLog.add(comboDay);
                panLog.resetKeyboardActions();*/
                
        }               
    }
    
    
    private int getDays(int month, boolean isLeap) {
    	
    	int days = 0;
    	if(month == 0 || month == 2 || month == 4 || month == 6
				|| month == 7 || month == 9 || month == 11) {
			
    		days = 31;
		}else if (month == 3 || month == 5 || month == 8 || month == 10) {
			
			days = 30;
		}else if(month == 1){
			if(isLeap == true) {
				
				days = 29;
			}else {
				
				days = 28;
			}
		}
    	
    	return days;
    }

    private void boitePwdErreur()
    {
        JOptionPane.showMessageDialog(null, 
                                      "Vous n'avez pas rempli tous les champs obligatoire",
                                      "Erreur", 
                                      JOptionPane.ERROR_MESSAGE);
    }
    
    private void boiteSucces()
    {
        JOptionPane.showMessageDialog(null, 
                                      "Compte Creer",
                                      "Information", 
                                      JOptionPane.INFORMATION_MESSAGE);
    }

    /*public String getNomUser(){
    	return nomU;
    }
    
    public String getPrenomUser(){
    	return prenomU;
    }*/
    
    public String getDateUser(){
    	return dateU;
    }
    
    public void setDateUser(String _date){
    	dateU = _date;
    }
    
    
    public Calendrier getCalendrier() {
    	return c;
    }
    
    /*public String getRueUser(){
    	return rueU;
    }
    
    public String getVilleUser(){
    	return villeU;
    }
    
    public String getPaysUser(){
    	return paysU;
    }
    
    public String getTelPUser(){
    	return telpU;
    }
    
    public String getTelFUser(){
    	return telfU;
    }
    
    public String getTelBUser(){
    	return telbU;
    }
    
    public String getEmailUser(){
    	return emailU;
    }
    
    public String getPwd1User(){
    	return pwdU1;
    }
    
    public String getPwd2User(){
    	return pwdU2;
    }*/
}
